package linz

import java.io.File


/**
 * 内置函数介绍
 */
fun main() {
    apply()
    run()
    with()
    alsoBuildIn()
}

/**
 * name.takeIf{true/false}
 * true: 直接返回那么本身
 * false： 直接返回null
 */
fun takeIfBuildIn(){
    val name = "Kotlin"
    val  str = name.takeIf { checkPermissionAction(name, "adsfasdf") } ?: "权限不够"
}

/**
 * name.takeUnless{true/false}
 * false: 直接返回那么本身
 * true： 直接返回null
 */
fun takeUnless(){

}


fun checkPermissionAction(name: String, password: String): Boolean = name.length > 3


fun alsoBuildIn(){
    val  file = File("d://")

    //匿名函数里面做的事情， 和sourceFile无关，永远返回file本身
    val sourceFile = file.also {
        file.setReadable(true)
        file.setWritable(true)
        println(file.readLines())
    }.also {
        it.setWritable(true)
    }
}


fun with(){
    val str = "Hello World"
    //具名
    val r = with(str, ::isLong)
    val r2 = with(r, ::showText)
    val r3 = with(r2, ::mapText)
    with(r3,::println)

    with(str, ::isLong)

    //匿名
    with(with(with(str){
        length
    }){
        "$this"
    }){
        println(this)
    }

}

fun isLong(str:String) = str.length>5

fun showText(isLong:Boolean) = if (isLong) "你的字符串合格" else "不合格"

fun mapText(show:String) = "【$show】"

fun run(){
    val str = ""

    val r2 = str.run(::isLong)
        .run(::showText)
        .run(::mapText)

    str.run(::isLong)

    println(r2)

    val r3 = str.let(::isLong)
        .let(::showText)
        .let(::mapText)

    str.run {
        isLong(this) //
        "" //最后一行返回值
    }
}


/**
 * Apply 内置函数始终返回info本身
 */
fun apply(){

    val info = "Hello World"
    println("output :${info.length}")
    println("output :${info[info.length - 1]}")
    println("output :${info.toLowerCase()}")

    println()
    info.apply {
        println("output :${length}")
        println("output :${this[info.length - 1]}")
        println("output :${toLowerCase()}")
    }

    //------------------------------------------

    //普通写法
    val  file = File("")
    file.setExecutable(true)
    file.setReadable(true)
    println(file.readLines())

    // apply 写法
    /*val fileNew: File =*/ file.apply {
        setExecutable(true)
        setReadable(true)
        println(file.readLines())
    }

    file.apply {
        setExecutable(true)
    }.apply {
        setReadable(true)
    }.apply {
        println(file.readLines())
    }
}